#include "comm.hpp"

using namespace std;

class Init
{
public:
    Init()
    {
        bool r = MakeFifo();
        if(!r)
        {
            return;
        }

        key_t key = GetKey();
        cout << "key: " << ToHex(key) << endl;

        int shmid = CreateShm(key);
        cout << "shmid: " << shmid << endl;

        cout << "开始将shm映射到进程的地址空间中" << endl;
        
        s = (char *)shmat(shmid, nullptr, 0);
        
        fd = open(FileName.c_str(), O_RDONLY);
    }

    ~Init()
    {
        shmdt(s);
        cout << "开始将shm从进程的地址空间中移除" << endl;
        
        shmctl(shmid, IPC_RMID, nullptr);
        cout << "开始将shm从OS中移除" << endl;
        
        close(fd);
        unlink(FileName.c_str());
    }
public:
    int shmid;
    int fd;
    char *s;
};

int main()
{
    Init init;

    while(true)
    {
        int code = 0;
        ssize_t n = read(init.fd, &code, sizeof(code));
        if(n > 0)
        {
            cout << "共享的内容: " << init.s << endl;
            sleep(1);
        }
        else if(n == 0)
        {
            break;
        }
    }

    return 0;
}
